<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\AppException;
use App\Models\Comment;
use App\Services\ArticleService;
use App\Services\CommentService;
use App\Services\SettingService;
use App\Services\UserService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;
use Laravel\Lumen\Application;
use Laravel\Lumen\Http\Redirector;
use Laravel\Lumen\Http\ResponseFactory;
use Laravel\Lumen\Routing\Controller;

class IndexController extends Controller
{

    /**
     * 后台登录
     * @param Request $request
     * @param UserService $userService
     * @return Response|View|Application|ResponseFactory
     * @throws AppException
     * @throws ValidationException
     */
    public function login(Request $request, UserService $userService)
    {
        if ($request->isMethod('get')) {
            return view('admin.login');
        }

        $this->validate($request, [
            'username'        => 'bail|required|string|max:20',
            'password'        => 'bail|required|string|min:6|max:30',
            //'captcha_ticket'  => 'bail|required|string',
            //'captcha_randstr' => 'bail|required|string',
        ]);

        /*$userService->checkTencentCaptcha(
            $request->input('captcha_ticket'),
            $request->input('captcha_randstr'),
            $request->ip()
        );*/

        $username = $request->input('username');
        $password = $request->input('password');

        $user = $userService->login($username, $password);
        $lastLoginTime = $user->login_time;

        $user->login_time = time();
        $user->save();

        $loginInfo = $user->id . '|' . $lastLoginTime . '|' . $user->login_time;

        $cookie = Cookie::make('login_user', encrypt($loginInfo));

        return success()->withCookie($cookie);
    }

    /**
     * 退出登录
     * @return RedirectResponse|Redirector
     */
    public function logout()
    {
        $cookie = Cookie::forget('login_user');
        return redirect('/admin/login')->withCookie($cookie);
    }

    /**
     * 后台框架页
     * @param SettingService $settingService
     * @return View|Application
     * @throws AppException
     */
    public function index(SettingService $settingService)
    {
        $user = Auth::user();
        $setting = $settingService->getSetting();
        $newComment = Comment::where('created_at', '>', $user->lastLoginTime)->first();

        $data = [
            'avatar'     => $setting->master_avatar,
            'username'   => $user->username,
            'newComment' => $newComment ? true : false,
        ];

        return view('admin.index', $data);
    }

    /**
     * 信息统计页
     * @param Request $request
     * @param ArticleService $articleService
     * @param CommentService $commentService
     * @param SettingService $settingService
     * @return View|Application
     */
    public function main(Request $request, ArticleService $articleService, CommentService $commentService, SettingService $settingService)
    {
        $user = Auth::user();
        $articleCount0 = $articleService->getCountByStatus(0);
        $articleCount1 = $articleService->getCountByStatus(1);
        $articleCount2 = $articleService->getCountByStatus(2);
        $commentCount1 = $commentService->getCount();
        $commentCount2 = $commentService->getCountAfterTime($user->lastLoginTime);
        $mysqlVersion = $settingService->getMysqlVersion();

        $data = [
            'username'       => $user->username,
            'lastLoginTime'  => $user->lastLoginTime,
            'userAgent'      => $request->server('HTTP_USER_AGENT'),
            'httpHost'       => $request->server('HTTP_HOST'),
            'serverSoftware' => $request->server('SERVER_SOFTWARE'),
            'articleCount0'  => $articleCount0,
            'articleCount1'  => $articleCount1,
            'articleCount2'  => $articleCount2,
            'commentCount1'  => $commentCount1,
            'commentCount2'  => $commentCount2,
            'mysqlVersion'   => $mysqlVersion,
        ];

        return view('admin.main', $data);
    }

    /**
     * 修改密码
     * @param Request $request
     * @param UserService $userService
     * @return Response|View|Application|ResponseFactory
     * @throws AppException
     * @throws ValidationException
     */
    public function password(Request $request, UserService $userService)
    {
        if ($request->isMethod('get')) {
            return view('admin.password');
        }

        $this->validate($request, [
            'password_old' => 'bail|required|string|min:6|max:30',
            'password_new' => 'bail|required|string|min:6|max:30',
        ]);

        $passwordOld = $request->input('password_old');
        $passwordNew = $request->input('password_new');

        $user = Auth::user();

        $userService->changePassword($user, $passwordOld, $passwordNew);

        return success();
    }

    /**
     * 参数设置
     * @param Request $request
     * @param SettingService $settingService
     * @return Response|View|Application|ResponseFactory
     * @throws AppException
     */
    public function setting(Request $request, SettingService $settingService)
    {
        if ($request->isMethod('get')) {
            $setting = $settingService->getSetting();
            $data = $setting->toArray();
            return view('admin.setting', $data);
        }

        $data = $request->input();
        $settingService->update($data);

        return success();
    }

    /**
     * CKFinder浏览+上传
     */
    public function ckfinder()
    {
        require_once base_path('app/Libs/CKFinder/core/connector/php/connector.php');
    }

}
